<?php

class vtnsResponse extends sfWebResponse
{
    private $version_query = '';


    public function initialize(sfEventDispatcher $dispatcher, $options = array())
    {
        parent::initialize($dispatcher, $options);

        $version = sfConfig::get('sf_master_cache_version');
        if ($version)
            $this->version_query = '?v='. (($version == 'random') ? rand(1,442) : $version);

        // Platform for Privacy Preferences headers, see http://www.w3.org/P3P/
        // Used by IE to block or accept cookies on an iframe page
        $this->setHttpHeader('P3P', 'CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT"');
        $this->addCacheControlHttpHeader('private, max-age=0');
        $this->setHttpHeader('Expires', '-1');
    }


    public function getStylesheets($position = self::ALL)
    {
        $stylesheets = parent::getStylesheets($position);
        if (self::RAW === $position)
            return $stylesheets;
        else
            return $this->addMasterCacheVersion($stylesheets, 'css');
    }


    public function getJavascripts($position = self::ALL)
    {
        $javascripts = parent::getJavascripts($position);
        if (self::RAW === $position)
            return $javascripts;
        else
            return $this->addMasterCacheVersion($javascripts, 'js');
    }


    private function addMasterCacheVersion($base_assets, $ext)
    {
        $final_assets = array();
        foreach ($base_assets as $file => $options)
            $final_assets[$this->addVersionString($file, $ext)] = $this->setAbsolute($options);
        return $final_assets;
    }


    /**
     * This functions adds the cache parameter to all scripts, the version
     * string ?v=<sf_master_cache_version> is added after the extension.
     *
     * Complete URLs containing a '://' are kept unchanged.
     */
    private function addVersionString($file, $ext)
    {
        if (strpos($file, '://') !== false)
            return $file;

        // We need an extenstion to check for the file existence and to add the query string
        if (strpos(basename($file), '.'.$ext) === false)
            $file .= '.'.$ext;

        // Append cache-version query
        $file .= $this->version_query;

        return $file;
    }


    /**
     * Facebook needs absolute URLs for stylesheets and javascripts in FBML.
     * We use absolute URLs in IFrame mode too, although this may not be required.
     */
    private function setAbsolute($options)
    {
        if (!is_array($options))
            $options = array();
        $options['absolute'] = true;
        return $options;
    }
}

